<template>
  <div class="min-h-screen flex items-center justify-center bg-base-200">
    <div class="card w-full max-w-md shadow-2xl bg-base-100">
      <div class="card-body">
        <!-- 标题和切换按钮 -->
        <h2 class="card-title justify-center text-2xl mb-4">
          {{ isLogin ? '登录' : '注册' }}
        </h2>

        <!-- 切换登录/注册 -->
        <div class="tabs tabs-boxed justify-center mb-4">
          <a class="tab" :class="{ 'tab-active': isLogin }" @click="isLogin = true">登录</a>
          <a class="tab" :class="{ 'tab-active': !isLogin }" @click="isLogin = false">注册</a>
        </div>

        <!-- 错误提示 -->
        <div v-if="errorMessage" class="alert alert-error mb-4">
          <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          <span>{{ errorMessage }}</span>
        </div>

        <!-- 成功提示 -->
        <div v-if="successMessage" class="alert alert-success mb-4">
          <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          <span>{{ successMessage }}</span>
        </div>

        <!-- 登录表单 -->
        <form v-if="isLogin" @submit.prevent="handleLogin" class="space-y-4">
          <div class="form-control">
            <label class="label">
              <span class="label-text">邮箱</span>
            </label>
            <input type="email" placeholder="请输入邮箱" class="input input-bordered" v-model="loginForm.email" required />
          </div>

          <div class="form-control">
            <label class="label">
              <span class="label-text">密码</span>
            </label>
            <input type="password" placeholder="请输入密码" class="input input-bordered" v-model="loginForm.password" required />
          </div>

          <div class="form-control mt-6">
            <button type="submit" class="btn btn-primary" :disabled="loading">
              <span v-if="loading" class="loading loading-spinner loading-sm"></span>
              {{ loading ? '登录中...' : '登录' }}
            </button>
          </div>
        </form>

        <!-- 注册表单 -->
        <form v-else @submit.prevent="handleRegister" class="space-y-4">
          <div class="form-control">
            <label class="label">
              <span class="label-text">邮箱</span>
            </label>
            <input type="email" placeholder="请输入邮箱" class="input input-bordered" v-model="registerForm.email" required />
          </div>

          <div class="form-control">
            <label class="label">
              <span class="label-text">密码</span>
              <span class="label-text-alt">至少 6 个字符</span>
            </label>
            <input type="password" placeholder="请输入密码" class="input input-bordered" v-model="registerForm.password" required minlength="6" />
          </div>

          <div class="form-control">
            <label class="label">
              <span class="label-text">昵称</span>
            </label>
            <input type="text" placeholder="请输入昵称" class="input input-bordered" v-model="registerForm.nickname" required />
          </div>

          <div class="grid grid-cols-2 gap-4">
            <div class="form-control">
              <label class="label">
                <span class="label-text">年龄</span>
              </label>
              <input type="number" placeholder="年龄（可选）" class="input input-bordered" v-model.number="registerForm.age" min="0" max="150" />
            </div>

            <div class="form-control">
              <label class="label">
                <span class="label-text">性别</span>
              </label>
              <select class="select select-bordered" v-model="registerForm.sex">
                <option value="">请选择（可选）</option>
                <option value="男">男</option>
                <option value="女">女</option>
              </select>
            </div>
          </div>

          <div class="form-control mt-6">
            <button type="submit" class="btn btn-primary" :disabled="loading">
              <span v-if="loading" class="loading loading-spinner loading-sm"></span>
              {{ loading ? '注册中...' : '注册' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { trpc } from '../trpc'
import type { LoginInput, RegisterInput } from '@shared/types'

// 表单状态
const isLogin = ref(true)
const loading = ref(false)
const errorMessage = ref('')
const successMessage = ref('')

// 登录表单
const loginForm = ref<LoginInput>({
  email: '',
  password: ''
})

// 注册表单
const registerForm = ref<RegisterInput>({
  email: '',
  password: '',
  nickname: '',
  age: undefined,
  sex: undefined
})

// 清除消息
const clearMessages = () => {
  errorMessage.value = ''
  successMessage.value = ''
}

// 处理登录
const handleLogin = async () => {
  clearMessages()
  loading.value = true

  try {
    // 清理数据，只发送非空字段
    const data: LoginInput = {
      email: loginForm.value.email.trim(),
      password: loginForm.value.password
    }

    const result = await trpc.login.mutate(data)

    // 保存 token 和用户信息到 localStorage
    localStorage.setItem('token', result.token)
    localStorage.setItem('user', JSON.stringify(result.user))

    successMessage.value = '登录成功！'

    // 延迟跳转或触发事件
    setTimeout(() => {
      // 可以在这里触发路由跳转或 emit 事件
      window.location.reload()
    }, 1000)
  } catch (error: any) {
    errorMessage.value = error.message || '登录失败，请检查邮箱和密码'
  } finally {
    loading.value = false
  }
}

// 处理注册
const handleRegister = async () => {
  clearMessages()
  loading.value = true

  try {
    // 清理数据
    const data: RegisterInput = {
      email: registerForm.value.email.trim(),
      password: registerForm.value.password,
      nickname: registerForm.value.nickname.trim(),
      age: registerForm.value.age || undefined,
      sex: registerForm.value.sex || undefined
    }

    const result = await trpc.register.mutate(data)

    // 保存 token 和用户信息到 localStorage
    localStorage.setItem('token', result.token)
    localStorage.setItem('user', JSON.stringify(result.user))

    successMessage.value = '注册成功！'

    // 延迟跳转
    setTimeout(() => {
      window.location.reload()
    }, 1000)
  } catch (error: any) {
    errorMessage.value = error.message || '注册失败，请重试'
  } finally {
    loading.value = false
  }
}

// 切换表单时清除消息
const watchIsLogin = () => {
  clearMessages()
}
</script>

<style scoped>
/* 额外的样式可以在这里添加 */
</style>
